package dev.bong.controller;

import dev.bong.pojo.entity.User;
import dev.bong.pojo.result.Result;

import dev.bong.service.AdminService;
import dev.bong.utils.JwtUtil;
import dev.bong.utils.Md5Util;
import dev.bong.vo.schedule.ScheduleVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import java.util.concurrent.TimeUnit;



@RestController
@RequestMapping("/pre")
@Api(value = "前置操作", tags = "前置操作")
@Slf4j
public class PreController {

    @Autowired
    private AdminService adminService;

    @Autowired
    private RedisTemplate redisTemplate;


    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "用户登录")
    public Result login(String account,String password){


        log.info(account,password);
        User user= adminService.findByUserAccount(account);
        log.info(user.toString());
        if(user==null){
            return Result.error("用户不存在");
        }
        String semester=adminService.getCurrentSemester();

        if(Md5Util.getMD5String(password).equals(user.getUserPassword())){
            Map<String,Object> claims=new HashMap<>();
            claims.put("userId",user.getId());
            claims.put("userAccount",user.getUserName());
            claims.put("username",user.getUserName());
            claims.put("semester",semester);

            String token= JwtUtil.genToken(claims);

            // 把token存储到redis中
            ValueOperations<String,String> operations = redisTemplate.opsForValue();
            operations.set(token,token,30,TimeUnit.MINUTES);

            return Result.success(token);

        }
        return Result.error("密码错误");

    }


    @GetMapping("/schedule")
    @ApiOperation(value = "获取课表", notes = "获取课表")
    public Result<List<ScheduleVo>> getSchedule(){

        List<ScheduleVo> list=adminService.getScheduleList();
        return Result.success(list);
    }


}

